﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Detective.Components.Base;
using Detective.Helpers;
using Detective.World;

namespace Detective.View.Base
{
    public abstract class BaseMdiView : BaseComponent, IView
    {
        private List<IView>
            _viewZOrder = new List<IView>();

        public bool IsWantRefresh = true;

        public bool IsHasChilds
        {
            get { return _viewZOrder.Count > 0; }
        }

        public override int GetDelayMilliSeconds()
        {
            return Constants.FPS60;
        }

        protected override void OnDelay(GameTime gameTime)
        {
            if (IsWantRefresh)
            {
                RefreshView();
            }
        }

        public void Show(IChildView view)
        {
            view.Parent = this;

            view.LeftMargin = 2;
            view.TopMargin = 2;

            view.PositionX = (Console.WindowWidth - view.Width) / 2;
            view.PositionY = _viewZOrder.Count * 2 + 1;

            _viewZOrder.Add(view);

            IsWantRefresh = true;
        }

        public TView Show<TView>()
            where TView : IChildView, new()
        {
            var view = new TView();

            Show(view);

            return view;
        }

        internal void CloseMe(IChildView view)
        {
            _viewZOrder.Remove(view);
            view.ClearView();
            view.Parent = null;

            IsWantRefresh = true;
        }

        public virtual void OnKeyDown(KeyEventArgs arg)
        {
            if (IsHasChilds)
            {
                arg.Handled = true;

                _viewZOrder[_viewZOrder.Count - 1].OnKeyDown(arg);
            }
        }

        public virtual void OnKeyUp(KeyEventArgs arg)
        {
            if (IsHasChilds)
            {
                arg.Handled = true;

                _viewZOrder[_viewZOrder.Count - 1].OnKeyUp(arg);
            }
        }

        public void RefreshView()
        {
            if (IsHasChilds)
            {
                _viewZOrder[_viewZOrder.Count - 1].RefreshView();
            }
            else
            {
                OnRefreshMdiView();
            }

            IsWantRefresh = false;
        }

        protected virtual void OnRefreshMdiView()
        {
            
        }
    }
}
